import React, {Component} from 'react'
import {connect} from 'react-redux'
import MusicItem from './music-item.jsx'
import Uploader from '../uploader.jsx'
import Progress from '../progress.jsx'
import F from 'lodash/fp'
import {uploadingMusic, uploadedMusic, failedUploadMusic, deletedMusic, deleteingMusic} from '../../actions/content-change'

const UploadPick = props => <button ref={props.ready} className="am-btn am-btn-default am-btn-sm">+上传音乐</button>

const musicUploader = props => {
    let {list, curSrc, selectMusic, selected} = props
    let delMusic = id => {
        layer.confirm('你确认要删除吗？', {icon: 3, title:'提示'}, index => {
            props.deleteingMusic(id)
            layer.colse(index)
        })
    }
    let genMusicItem = t => <MusicItem {...t} 
        curSrc={curSrc}
        key={t.id}
        play={props.play.bind(t, t.src)}
        pause={props.pause}
        delMusic={delMusic.bind(t, t.id)}
        delable
        select={selectMusic.bind(t, t)}
        selected={selected}
    />;

    let uploadFile2music = uploadFile => ({
        id: uploadFile.id,
        filename: uploadFile.name,
        status: 'uploading'
    })

    return (
        <div className="vip-music-wp">
            <ul>
                <li style={{height: 'unset'}}>
                    <div className="am-form-group am-form-file wp-upload-music">
                        { F.size(list) < 5 ?
                            <Uploader 
                                onQueued={F.compose(props.uploadingMusic, uploadFile2music)}
                                onSuccess={props.uploadedMusic}
                            >
                                <UploadPick uploaderPick />
                                <a className="music-upload" href="/article/changjianwenti/6964.html" target="_blank">(如何上传音乐)</a>
                                <Progress uploaderProgress />
                            </Uploader>
                        : <p>您上传的歌曲已达上限！</p> 
                        }
                    </div>
                    <span className="music-num">{F.size(list)}/5</span>
                </li>
                {F.map(genMusicItem)(list)}
            </ul>
        </div>
    )
}


class MusicUploader extends Component {
    render() {
        return musicUploader(this.props)
    }
}

const delMusic = ({id}) => $.ajax(`/user-songs/delete/${id}`).then(_=>id)
const then = fn => promise => promise.then(fn)
export default connect(
    ({music}) => ({
        list: music.userUpload.list,
        curSrc: music.curSrc,
    })
    , (dispatch, props) => ({
        uploadingMusic: F.compose(dispatch, uploadingMusic),
        uploadedMusic: F.compose(dispatch, uploadedMusic),
        failedUploadMusic: F.compose(dispatch, failedUploadMusic),
        deletedMusic:  F.compose(dispatch, deletedMusic),
        deleteingMusic: F.compose(then(dispatch), then(deletedMusic), delMusic, deleteingMusic),
    })
)(MusicUploader)